package com.ruoyi.datastatistics.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.annotation.InterceptorIgnore;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DateUtil;
import com.ruoyi.datastatistics.domain.ElectricityMeterHistoryData;
import com.ruoyi.datastatistics.domain.ElectricityRealtimegatherdataXb;
import com.ruoyi.datastatistics.domain.MeterHistoryData;
import com.ruoyi.datastatistics.service.IElectricityRealtimegatherdataXbService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.datastatistics.mapper.ElectricityMeterHistoryDataMapper;
import com.ruoyi.datastatistics.domain.ElectricityMeterHistoryData;
import com.ruoyi.datastatistics.service.IElectricityMeterHistoryDataService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.transaction.annotation.Transactional;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
/**
 * 电-历史数据Service业务层处理
 *
 * @author gdqt
 * @date 2025-03-10
 */
@Service
public class ElectricityMeterHistoryDataServiceImpl extends ServiceImpl
        <ElectricityMeterHistoryDataMapper, ElectricityMeterHistoryData> implements IElectricityMeterHistoryDataService
{
    @Autowired
    private ElectricityMeterHistoryDataMapper electricityMeterHistoryDataMapper;

    @Autowired
    private IElectricityRealtimegatherdataXbService electricityRealtimegatherdataXbService;

    /**
     * 查询小-历史数据
     *
     * @param ID 小-历史数据主键
     * @return 小-历史数据
     */
    @Override
    public ElectricityMeterHistoryData selectMeterHistoryDataByID(Long ID)
    {
        return electricityMeterHistoryDataMapper.selectMeterHistoryDataByID(ID);
    }

    /**
     * 查询小-历史数据列表
     *
     * @param meterHistoryData 小-历史数据
     * @return 小-历史数据
     */
    @Override
    public List<ElectricityMeterHistoryData> selectMeterHistoryDataList(ElectricityMeterHistoryData meterHistoryData) throws ParseException {
        if (meterHistoryData.getParams().get("beginReadDate") == null || meterHistoryData.getParams().get("endReadDate") == null){
            SimpleDateFormat foramt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            meterHistoryData.getParams().put("beginReadDate", DateUtil.past7Days());
            meterHistoryData.getParams().put("endReadDate",foramt.format(new Date()));
        }
        return electricityMeterHistoryDataMapper.selectMeterHistoryDataList(meterHistoryData);
    }
    /**
     * 查询小-历史数据列表
     *
     * @param meterHistoryData 小-历史数据
     * @return 小-历史数据
     */
    @Override
    public List<ElectricityMeterHistoryData> selectMeterHistoryDataList2(ElectricityMeterHistoryData meterHistoryData) throws ParseException {
        if (meterHistoryData.getParams().get("beginReadDate") == null || meterHistoryData.getParams().get("endReadDate") == null){
            SimpleDateFormat foramt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            meterHistoryData.getParams().put("beginReadDate", DateUtil.past7Days());
            meterHistoryData.getParams().put("endReadDate",foramt.format(new Date()));
        }
        return electricityMeterHistoryDataMapper.selectMeterHistoryDataList(meterHistoryData);
    }
    /**
     * 新增小-历史数据
     *
     * @param meterHistoryData 小-历史数据
     * @return 结果
     */
    @Override
    public int insertMeterHistoryData(ElectricityMeterHistoryData meterHistoryData)
    {
        return electricityMeterHistoryDataMapper.insert(meterHistoryData);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    @InterceptorIgnore(tenantLine = "true")
    public AjaxResult insertMeterHistoryDataAndRealData(ElectricityMeterHistoryData meterHistoryData)
    {

        //验证逻辑：必填项-累计读数，正向读数与累计读数一致，反向读数默认为零。
        // 当前录入数据比上期读数（查找当前录入时间之前的历史数据）要大，用location_nb查找历史数据。
        // LambdaQueryWrapper<ElectricityMeterHistoryData>  queryWrapper = new LambdaQueryWrapper<>();
        // queryWrapper.eq(ElectricityMeterHistoryData::getLocationNb,meterHistoryData.getLocationNb());
        // queryWrapper.eq(ElectricityMeterHistoryData::getTenantId,meterHistoryData.getTenantId());
        // queryWrapper.lt(ElectricityMeterHistoryData::getReadDate,meterHistoryData.getReadDate());
        // queryWrapper.ge(ElectricityMeterHistoryData::getCombinationActiveEnergy1
        //         ,meterHistoryData.getCombinationActiveEnergy1());



        Long countValidate = electricityMeterHistoryDataMapper.selectListExtendCount(meterHistoryData);
        if (countValidate > 0){
            return AjaxResult.error("录入数据比上期读数要大！");
        }

        //
        ElectricityRealtimegatherdataXb electricityRealtimegatherdataXb = new ElectricityRealtimegatherdataXb();
        BeanUtils.copyProperties(meterHistoryData,electricityRealtimegatherdataXb);
        int count =  electricityMeterHistoryDataMapper.insert(meterHistoryData);
        if (count < 1){
               return AjaxResult.error("历史表插入失败");
        }
        //实时表存在即更新  不存在则新增
        Long countRealExist = electricityRealtimegatherdataXbService.selectListCountByParams(electricityRealtimegatherdataXb);
        if(countRealExist == 1L){
            LambdaUpdateWrapper<ElectricityRealtimegatherdataXb> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(ElectricityRealtimegatherdataXb::getLocationNb ,electricityRealtimegatherdataXb.getLocationNb());

            boolean resultReal = electricityRealtimegatherdataXbService.update(electricityRealtimegatherdataXb, updateWrapper);
            if(!resultReal){
                throw new RuntimeException("更新失败!");
            }
        }else if(countRealExist == 0L){
            int countReal = electricityRealtimegatherdataXbService.insertRealtimegatherdataXb(electricityRealtimegatherdataXb);
            if(countReal <1){
                throw new RuntimeException("插入失败!");
            }
        }else{
            throw new RuntimeException("实时表一个location_nb存在多条重复数据!");
        }


        return AjaxResult.success();

    }

    @Transactional
    @Override
    public int batchinsertMeterHistoryData(List<ElectricityMeterHistoryData> list)
    {
        this.saveBatch(list);
        return 1;
    }


    @Transactional
    @Override
    public int batchinsertMeterHistoryDataR(List<ElectricityMeterHistoryData> list)
    {
        return electricityMeterHistoryDataMapper.insertAllBatch(list);
        // return 1;
    }

    /**
     * 修改小-历史数据
     *
     * @param meterHistoryData 小-历史数据
     * @return 结果
     */
    @Override
    public int updateMeterHistoryData(ElectricityMeterHistoryData meterHistoryData)
    {
        return electricityMeterHistoryDataMapper.updateById(meterHistoryData);
    }

    /**
     * 批量删除小-历史数据
     *
     * @param IDs 需要删除的小-历史数据主键
     * @return 结果
     */
    @Override
    public int deleteMeterHistoryDataByIDs(Long[] IDs)
    {
        return electricityMeterHistoryDataMapper.deleteMeterHistoryDataByIDs(IDs);
    }

    /**
     * 删除小-历史数据信息
     *
     * @param ID 小-历史数据主键
     * @return 结果
     */
    @Override
    public int deleteMeterHistoryDataByID(Long ID)
    {
        return electricityMeterHistoryDataMapper.deleteMeterHistoryDataByID(ID);
    }

    @Override
    public List<ElectricityMeterHistoryData> selectList(ElectricityMeterHistoryData meterHistoryData) {
        return electricityMeterHistoryDataMapper.selectList(meterHistoryData);
    }

    @Override
    public List<ElectricityMeterHistoryData> selectElectricityMeterHistoryDataLasted(Map<String, Object> paramsRequeest) {
        return electricityMeterHistoryDataMapper.selectElectricityMeterHistoryDataLasted(paramsRequeest);

    }

    @Override
    public List<ElectricityMeterHistoryData> selectElectricityMeterHistoryDataLastedMore(Map<String, Object> paramsRequeest) {
        return electricityMeterHistoryDataMapper.selectElectricityMeterHistoryDataLastedMore(paramsRequeest);
    }
}
